<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024-05-22 20:22:04
 * @LastEditors: toString
 * @LastEditTime: 2024-12-13 18:07:30
 * @FilePath: \chain-link-api-front\src\views\assetManagement\index.vue
 * @Description: 资产管理
-->
<template>
  <Header>
    <template #title>{{ t('title.AssetManagement') }}</template>
  </Header>
  <div class="generate">
    <el-button type="primary" round @click="handleAdd">{{ t('assetManagement.AddAsset') }}</el-button>
  </div>

  <!--  新增资产-->
  <el-dialog v-model="addDialog" :title="t('assetManagement.AddAsset')" width="500" center @close="resetForm">
    <el-form :model="form" :rules="rules" ref="ruleRef" label-width="auto" style="max-width: 600px" label-position="top">
      <el-form-item prop="chainId" :label="t('assetManagement.SelectChainName')">
        <el-select v-model.trim="form.mainCoinType" :loading="loading"
                   :placeholder="t('assetManagement.SelectChainName')">
          <el-option v-for="(item, index) in chainList" :key="index" :label="item.chainName" :value="item.udunId" @click="handleSelect(item)"/>
        </el-select>
      </el-form-item>
      <el-form-item :label="t('assetManagement.CollectAddress')">
        <el-input v-model.trim="form.collectAddress" type="text" :placeholder="t('message.CollectTips')"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitAdd">
          {{ t('global.Submit') }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  修改资产-->
  <el-dialog v-model="editDialog" :title="t('global.Update')" width="500" center @close="resetForm">
    <el-form :model="editForm" :rules="rulesEdit" ref="ruleEditRef" label-width="auto" label-position="top" style="max-width: 600px">
      <el-form-item :label="t('assetManagement.SelectChainName')">
        <el-select v-model.trim="editForm.mainCoinType" disabled>
          <el-option v-for="(item, key) in invoiceData.configList" :key="key" :label="item.chainName"
                     :value="item.udunId"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="collectAddress" :label="t('assetManagement.CollectAddress')">
        <el-input v-model.trim="editForm.collectAddress" @focus="getInitValue($event, tag)"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitEdit(tag)">
          {{ t('global.Submit') }}
        </el-button>
      </div>
    </template>
  </el-dialog>


  <!--  修改手续费地址 -->
  <el-dialog v-model="modifyFeeDialog" :title="t('global.Update')" width="500" center @close="resetForm">
    <el-form :model="editForm" :rules="rulesEdit" ref="ruleEditRef" label-width="auto" label-position="top" style="max-width: 600px">
      <el-form-item :label="t('assetManagement.SelectChainName')">
        <el-select v-model.trim="editForm.mainCoinType" disabled>
          <el-option v-for="(item, key) in invoiceData.configList" :key="key" :label="item.chainName"
                     :value="item.udunId"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="collectAddress" :label="t('assetManagement.CollectAddress')">
        <el-input v-model.trim="editForm.collectAddress" @focus="getInitValue($event, tag)"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitEdit(tag)">
          {{ t('global.Submit') }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!--  手续费地址详情 dialog -->
  <el-dialog v-model="detailDialog" :title="t('devDoc.Detail')" width="1000" center @close="resetForm">
    <div class="myTable fee">
      <p class="title">{{ t('table.FeeAddress')}}: {{ detailForm.feeAddress ? detailForm.feeAddress : '-'}}</p>
      <p>{{ t('table.Balance')}}: {{ feeBalance}}</p>
    </div>

    <div class="myTable coll">
      <p class="title">{{ t('table.CollectAddress')}}: {{ collectionAddress}}</p>
      <el-table :data="collData" border style="width: auto; " v-loading="loading">
        <el-table-column prop="name" :label="t('table.Symbol')" width="" align="center"/>
        <el-table-column prop="balance" :label="t('table.Balance')" width="" align="center"/>
      </el-table>
    </div>


    <div class="myTable withdraw">
      <p class="title">{{ t('table.WithdrawAddress')}}: {{ detailForm.withdrawAddress ? detailForm.withdrawAddress : '-'}}</p>
      <el-table :data="withdrawData" border style="width: auto; " v-loading="loading">
        <el-table-column prop="name" :label="t('table.Symbol')" width="" align="center"/>
        <el-table-column prop="balance" :label="t('table.Balance')" width="" align="center"/>
      </el-table>
    </div>

  </el-dialog>

  <div class="table">
    <el-table :data="tableData" border style="width: 100%; height: 700px; overflow: auto;" v-loading="loading">
      <el-table-column prop="chainName" :label="t('table.ChainName')" width="auto" align="center"/>
      <el-table-column prop="feeAddress" width="400" align="center">
        <template #header>
          <span>{{ t('table.FeeAddress') }}</span>
          <el-tooltip class="box-item" effect="dark" :content="t('message.FeeAddressTips')" placement="top">
            <el-icon style="margin-left: 0.2rem"><QuestionFilled /></el-icon>
          </el-tooltip>
        </template>
        <template #default="scope">
          {{ scope.row.feeAddress }}
        </template>
      </el-table-column>
      <el-table-column prop="collectAddress" :label="t('table.CollectAddress')" width="400" align="center"/>
      <el-table-column prop="withdrawAddress" :label="t('table.WithdrawAddress')" width="400" align="center">
        <template #header>
          <span>{{ t('table.WithdrawAddress') }}</span>
          <el-tooltip class="box-item" effect="dark" :content="t('message.WithdrawAddressTips')" placement="top">
            <el-icon style="margin-left: 0.2rem"><QuestionFilled /></el-icon>
          </el-tooltip>
        </template>
        <template #default="scope">
          {{ scope.row.withdrawAddress }}
        </template>
      </el-table-column>
      <el-table-column prop="balance" :label="t('assetManagement.FeeBalance')" width="200" align="center" fixed="right"/>
      <el-table-column prop="withdrawBalance" :label="t('table.WithdrawBalance')" width="200" align="center" fixed="right"/>
      <el-table-column fixed="right" :label="t('global.Operation')" width="150" align="center">
        <template #default="scope">
          <div><el-button link type="danger" size="small" @click="handleDetail(scope)">{{t('button.ViewDetails')}}</el-button></div>
          <div><el-button link type="primary" size="small" @click="handleEdit(scope)">{{ t('global.Update') }}</el-button></div>
          <el-popconfirm title="修改手续费地址原手续费地址余额将清零,请再次确认!" @confirm="modifyFee(scope)" :width="400">
            <template #reference>
              <el-button link type="warning" size="small">更改手续费地址</el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="修改提现地址原提现地址余额将清零,请再次确认!" @confirm="modifyWithdraw(scope)" :width="400">
            <template #reference>
              <el-button link type="warning" size="small">更改提现地址</el-button>
            </template>
          </el-popconfirm>
          <div>
            <el-button link type="danger" size="small" @click="handleWithdraw(scope.row)">
              余额提现
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>

  <el-dialog v-model="withdrawDialogVisible" width="500" @close="handleCloseWithdrawDialog">
    <template #header>
      <div class="el-dialog__header">
        <div class="el-dialog__title">
          <span>
            余额提现
          </span>
          <el-popover
            placement="bottom"
            :width="250"
            trigger="hover"
            content="请自行选择从手续费地址或提现地址将余额提现到归集地址"
          >
            <template #reference>
              <el-icon style="vertical-align: middle;">
                <InfoFilled />
              </el-icon>
            </template>
          </el-popover>
        </div>
      </div>
    </template>

    <div>
      <el-form :label-position="'top'">

        <el-form-item label="币种" :label-position="'top'">
          <el-radio-group v-model="currency" @change="handleCurrency">
            <el-radio :value="1">
              主币
            </el-radio>
            <el-radio :value="2">
              代币
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="代币地址" :label-position="'top'" v-if="currency === 2">
          <el-input v-model="withdrawDialogObj.tokenAddress"></el-input>
        </el-form-item>

        <el-form-item label="手续费地址 / 提现地址" :label-position="'top'">
          <el-radio-group v-model="withdrawDialogObj.type" @change="handleType">
            <el-radio :value="1">
              手续费地址
            </el-radio>
            <el-radio :value="2">
              提现地址
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="withdrawDialogObj.type === 1 ? '手续费地址' : (withdrawDialogObj.type === 2 ? '提现地址' : '')" :label-position="'top'" >
          <el-input v-model="withdrawDialogObj.address" disabled></el-input>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCloseWithdrawDialog">
          取消提现
        </el-button>
        <el-button type="primary" @click="confirmWithdraw" v-loading.fullscreen.lock="fullscreenLoading">
          确定提现
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import {onMounted, reactive, ref, unref} from 'vue'
import {ElMessage, ElPagination, ElTable} from 'element-plus'
import Header from "../layout/header.vue";
import {addPocketAddress, getConfigList, getPocketList, updatePocketAddress, getPocketInfo, modifyFeeWithdraw, withdrawToCollectApi} from '../../require/api'
import {useI18n} from "vue-i18n";
import {formatTimestamp} from "@/utils/timeStamp.js";
import {QuestionFilled, InfoFilled} from "@element-plus/icons-vue";

const {t} = useI18n();

// 在组件被挂载后执行
onMounted(() => {
  getList();
  getChainList()
});
const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])
const chainList = ref([])
const loading = ref(false)
const addDialog = ref(false) // 新增资产dialog
const editDialog = ref(false) // 修改资产dialog
const detailDialog = ref(false) // 手续费地址详情dialog
const modifyFeeDialog = ref(false) // 修改手续费地址
const modifyWithdrawDialog = ref(false) // 修改提现地址地址
const ruleRef = ref(null)
const ruleEditRef = ref(null)

const fullscreenLoading = ref(false);
const withdrawDialogVisible = ref(false);
// 币种：1主币 2代币
const currency = ref(1);
const rowObj = ref({});
const withdrawDialogObj = ref({
  id: "",
  tokenAddress: "",
  type: 1,
  address: "",
});

// TODO 修改手续费地址  /  提现地址  多语
// 点击更改手续费地址 方法
async function modifyFee(scope){
  try{
    const params = {
      id: scope.row.id,
      type: modifyFeeForm.type,
    }
    const {code, data, message} = await modifyFeeWithdraw(params);
    if(code === 200){
      console.log(data)
      ElMessage.success('修改成功');
      await getList();
      modifyFeeDialog.value = false;
    }else{
      ElMessage.error(message)
    }
  }catch (e) {
    console.log(e)
  }
}

// 点击更改提现地址 方法
async function modifyWithdraw(scope){
  try{
    const params = {
      id: scope.row.id,
      type: modifyWithdrawForm.type,
    }
    const {code, data, message} = await modifyFeeWithdraw(params);
    if(code === 200){
      console.log(data)
      ElMessage.success('修改成功');
      await getList();
      modifyFeeDialog.value = false;
    }else{
      ElMessage.error(message)
    }
  }catch (e) {
    console.log(e)
  }
}

// 修改手续费地址
const modifyFeeForm = reactive({
  id: 0,
  type: '1', // 1:手续费地址 2:提现地址
})

// 修改提现地址
const modifyWithdrawForm = reactive({
  id: 0,
  type: '2', // 1:手续费地址 2:提现地址
})


// 新增资产 form
const form = reactive({
  /* chainId: '', */
  // mainCoinType: '', // udunId
  mainCoinType: undefined, // 初始化为一个空对象
  feeAddress: '',   //手续费地址
  collectAddress: '',  //归集地址
  withdrawAddress: '',   //提现地址
  chainName: ''
})

// 新增资产 选择链 方法
function handleSelect(item){
  form.mainCoinType = item.udunId;
  form.chainName = item.chainName;
}

// 新增资产 dialog
async function handleAdd() {
  addDialog.value = true;
}

// // 修改表单
const editForm = reactive({
  id: '',
  mainCoinType: undefined, // 初始化为一个空对象
  // mainCoinType: '',
  feeAddress: '',   //手续费地址
  collectAddress: '',  //归集地址
  withdrawAddress: '',  //提现地址
  chainName: ''
})

const editParams = reactive({
  feeAddress: '',   //手续费地址
  collectAddress: '',  //归集地址
  withdrawAddress: '',  //提现地址
})

async function handleInputFee(newValue) {

}

async function getInitValue(e, tag) {
  console.log(e)
  console.log(tag)

}

// 表单验证规则
const rules = reactive({
  chainId: [
    {required: true, message: t('message.ChainNameNotNull'), trigger: 'blur'},
  ],
  feeAddress: [
    {required: true, message: t('message.FeeAddress'), trigger: 'blur'},
  ],
  collectAddress: [
    {required: true, message: t('message.CollectAddress'), trigger: 'blur'},
  ],
  withdrawAddress: [
    {required: true, message: t('message.WithdrawAddress'), trigger: 'blur'},
  ],
})

const rulesEdit = reactive({
  feeAddress: [
    {required: true, message: t('message.FeeAddress'), trigger: 'blur'},
  ],
  collectAddress: [
    {required: true, message: t('message.CollectAddress'), trigger: 'blur'},
  ],
  withdrawAddress: [
    {required: true, message: t('message.WithdrawAddress'), trigger: 'blur'},
  ],
})

/************* 修改开始 *******************/
// 原始值
const originalFeeAddress = ref('')
const originalCollectAddress = ref('')
const originalWithdrawAddress = ref('')

async function handleEdit({row}) {
  editDialog.value = true
  const {data} = await getConfigList();
  invoiceData.configList = data;
  editForm.mainCoinType = row.mainCoinType;
  editForm.id = row.id
  editForm.feeAddress = row.feeAddress
  editForm.collectAddress = row.collectAddress
  editForm.withdrawAddress = row.withdrawAddress

  // 确保originalFeeAddress, originalCollectAddress, originalWithdrawAddress是在editDialog打开时保存的原始值
  // 例如，在editDialog打开时保存原始值:
  originalFeeAddress.value = editForm.feeAddress;
  originalCollectAddress.value = editForm.collectAddress;
  originalWithdrawAddress.value = editForm.withdrawAddress;
}

// 提交修改
async function submitEdit(tag) {

  // 修改资产
  try {
    loading.value = true
    const chainData = unref(invoiceData.configList).filter(item => item.udunId === editForm.mainCoinType)
    const {code, msg} = await updatePocketAddress(
        {
          id: editForm.id,
          mainCoinType: editForm.mainCoinType,
          // feeAddress: originalFeeAddress.value === editForm.feeAddress ? '' : editForm.feeAddress,
          collectAddress: originalCollectAddress.value === editForm.collectAddress ? '' : editForm.collectAddress,
          // withdrawAddress: originalWithdrawAddress.value === editForm.withdrawAddress ? '' : editForm.withdrawAddress,
          chainName: chainData[0].chainName
        })
    editDialog.value = false
    pageIndex.value = 1
    if (code === 200) {
      // 如果没做修改,不弹提示
      if (
          // originalFeeAddress.value === editForm.feeAddress &&
          originalCollectAddress.value === editForm.collectAddress
          // originalWithdrawAddress.value === editForm.withdrawAddress
      ) {
        editDialog.value = false
      } else {
        ElMessage.success(t('message.EditSuccess'))
      }
    } else {
      ElMessage.error(msg)
    }
  } catch (e) {
    console.log(e)

  } finally {
    loading.value = false
    resetForm()
    await getList()
  }
}

/************* 修改结束 *******************/
const detailForm = reactive({
  feeAddress: '',
  collectionAddress: '',
  withdrawAddress: '',
  chainName: '',
  mainCoinType: ''
})

// 归集呆滞
const collectionAddress = ref()
// 查看手续费地址详情
const handleDetail = (scope) => {
  detailDialog.value = true
  detailForm.feeAddress = scope.row.feeAddress
  collectionAddress.value = scope.row.collectAddress
  detailForm.collectionAddress = scope.row.collectAddress
  detailForm.withdrawAddress = scope.row.withdrawAddress
  detailForm.chainName = scope.row.chainName
  detailForm.mainCoinType = scope.row.mainCoinType

  getPocketInfoFun(detailForm.feeAddress, detailForm.collectionAddress, detailForm.withdrawAddress, detailForm.chainName, detailForm.mainCoinType)

}

const feeBalance = ref()
const collData = ref([]) // 归集余额
const withdrawData = ref([]) // 提现余额


// 获取资产详情
async function getPocketInfoFun(feeAddress, collectionAddress, withdrawAddress, chainName, mainCoinType) {
  try {
    loading.value = true
    const {code, data, msg} = await getPocketInfo({
      feeAddress,
      collectionAddress,
      withdrawAddress,
      chainName,
      mainCoinType
    })
    feeBalance.value = data.feeBalance
    collData.value = data.collectionFee
    withdrawData.value = data.withdrawBalance
  } catch (e) {
    console.log(e)
  } finally {
    loading.value = false
  }
}

// 分页参数
const invoiceData = reactive({
  id: '',
  chainName: '',
  chainId: '',
  total: 0,
  pageSize: 10,
  pageNumber: 1,
  configList: [],
  tableData: [],
})

// 获取资产列表
async function getList() {
  try {
    loading.value = true
    const {code, data, msg} = await getPocketList({
      pageIndex: unref(pageIndex),
      pageSize: unref(pageSize),
    })
    if (code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 提交新增资产请求
async function submitAdd() {
    // if (
    //     // form.feeAddress.trim() === '' ||
    //     form.collectAddress.trim() === ''
    //     // form.withdrawAddress.trim() === ''
    // ) {
    //   ElMessage.error(t('message.InputAll'))
    //   return
    // }
    // 添加资产
    try {
      loading.value = true
      // const chainData = unref(chainList.value).filter(item => item.udunId === form.mainCoinType)
      if(!form.mainCoinType || !form.chainName){
        ElMessage.error(t('message.SelectChainName'))
        return
      }
      const {code, msg} = await addPocketAddress(
          {
            mainCoinType: form.mainCoinType,
            // feeAddress: form.feeAddress,
            collectAddress: form.collectAddress ? form.collectAddress : '',
            // withdrawAddress: form.withdrawAddress,
            chainName: form.chainName,
          })
      if (code === 200) {
        ElMessage.success(t('message.AddSuccess'))
        await getList()
        loading.value = false
        resetForm()
      } else {
        ElMessage.error(msg)
      }
    } catch (e) {
      console.log(e)
    } finally {
      loading.value = false
    }
}

// 重置表单
function resetForm() {
  addDialog.value = false;
  editDialog.value = false;
  form.mainCoinType = undefined
  // form.feeAddress = undefined
  form.collectAddress = undefined
  // form.withdrawAddress = undefined
  editForm.mainCoinType = undefined
  // editForm.feeAddress = undefined
  editForm.collectAddress = undefined
  // editForm.withdrawAddress = undefined

  feeBalance.value = undefined
  collData.value = undefined
  withdrawData.value = undefined
}

// 获取配置信息
async function getChainList() {
  const {data} = await getConfigList();
  chainList.value = data;
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 分页
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getList()
}

// 打开余额提现 dialog
function handleWithdraw(row) {
  rowObj.value = row;
  withdrawDialogObj.value.id = rowObj.value.id;
  withdrawDialogObj.value.address = rowObj.value.feeAddress;
  withdrawDialogVisible.value = true;
};

// 关闭余额提现 dialog
function handleCloseWithdrawDialog() {
  currency.value = 1;
  withdrawDialogObj.value = {
    id: "",
    tokenAddress: "",
    type: 1,
    address: "",
  };
  withdrawDialogVisible.value = false;
};

// 余额提现 dialog 确定按钮
function confirmWithdraw() {
  fullscreenLoading.value = true;
  withdrawToCollect();
};

async function withdrawToCollect() {
  try {
    let res = await withdrawToCollectApi({
      id: String(withdrawDialogObj.value.id),
      tokenAddress: String(withdrawDialogObj.value.tokenAddress),
      type: Number(withdrawDialogObj.value.type),
      address: String(withdrawDialogObj.value.address),
    });
    fullscreenLoading.value = false;
    if (res.code === 200) {
      ElMessage.success('提现成功');
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    fullscreenLoading.value = false;
    console.log('withdrawToCollectApi - error', error);
  }
};

function handleCurrency() {
  // 主币传空字符串，代币传代币地址
  if (currency.value === 1) {
    withdrawDialogObj.value.tokenAddress = "";
  }
};

function handleType() {
  if (withdrawDialogObj.value.type === 1) {
    // 手续费地址
    withdrawDialogObj.value.address = rowObj.value.feeAddress;
  } else if (withdrawDialogObj.value.type === 2) {
    // 提现地址
    withdrawDialogObj.value.address = rowObj.value.withdrawAddress;
  }
};

</script>

<style scoped lang="less">
.generate {
  text-align: left;
  margin: 10px
}
.myTable{
  .title{
    margin:.2rem 0 ;
  }
}

.fee{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}
.coll{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin: .5rem 0;
}

.withdraw{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}


</style>
